package com.wtwd.device.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author zdl
 * @date 2022/9/20 17:26
 */
@Component
public class FileServerFilter implements GlobalFilter, Ordered {

    private final static String FILETYPE = "multipart/form-data";
    private final static String FILE_SERVER = "http://127.0.0.1:";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest serverHttpRequest = exchange.getRequest();
        HttpHeaders headers = serverHttpRequest.getHeaders();
        String first = headers.getFirst(HttpHeaders.CONTENT_TYPE);
        if (first!=null && first.contains(FILETYPE)) {
            Route route = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
            Route newRoute = Route.async()
                    .asyncPredicate(route.getPredicate())
                    .filters(route.getFilters())
                    .id(route.getId())
                    .order(route.getOrder())
                    .uri(FILE_SERVER + FileServerPortEnum.getPort(route.getId()))
                    .build();
            exchange.getAttributes().put(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR, newRoute);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 2;
    }

    enum FileServerPortEnum {
        haifit(5001, "app"), hfit(5002, "hfit-app"), vastFit(5003, "vastfit-app"), managementPlatform(6001, "management-platform");

        private int port;
        private String project;

        FileServerPortEnum(int port, String project) {
            this.port = port;
            this.project = project;
        }

        public static int getPort(String project) {
            for (FileServerPortEnum value : FileServerPortEnum.values()) {
                if (value.project.equals(project)) {
                    return value.port;
                }
            }
            return 0;
        }
    }
}
